package edu.sandau.b230151.b23015121.controller;
import edu.sandau.b230151.b23015121.model.Pet;
import edu.sandau.b230151.b23015121.service.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;

@Controller
@RequestMapping("pet")
public class PetController {
    //static int nextid=3; 按顺序添加id
    @Autowired
    private PetService petService;
    @RequestMapping("list")
    public String list(ModelMap map, Pet pet){
        if("".equals(pet.getName())) {
            pet.setName(null);
        }
        if("".equals(pet.getPetcategory())) {
            pet.setPetcategory(null);
        }
        map.put("petList",petService.findAll(pet));

        return "/pet/list";
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id){
        System.out.println("id:"+id);
        petService.deleteById(id);
        return "redirect:/pet/list";
    }

    @RequestMapping("create")
    public String create(){
        return "pet/create";
    }

    @RequestMapping("save")
    public String save(Pet s){
        if(s.getId() == null){
            s.setId(UUID.randomUUID().toString());// 设置新的 ID
            petService.save(s); // 保存操作
        } else {
            petService.update(s); // 更新操作
        }
        System.out.println(s.getName());
        System.out.println(s.getPetcategory());
        return "redirect:/pet/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map){
        Pet s=petService.getReferenceById(id);
        map.put("pet",s);
        return "pet/update";
    }
}
